#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <time.h>

int cells[30][30];
int high=20;
int width=30;
int i,j;

void gotoxy(int x,int y)//
{
    HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos;
    pos.X = x;
    pos.Y = y;
    SetConsoleCursorPosition(handle,pos);
}

void start()
{
	for (i=0;i<high;i++)
		for (j=0;j<width;j++)
		{
			cells[i][j] = rand()%2;
		}
}

void show()
{
	gotoxy(0,0);
	for (i=0;i<=high;i++)
	{
		for (j=0;j<=width;j++)
		{
			if (cells[i][j]==1)
				printf("*");
			else
				printf(" ");
		}
		printf("\n");
	}
	Sleep(150);
}

void input()
{

}

void outinput()
{
    int cells2[20][30];
    int near12;
    for (i=0;i<=high-1;i++)
	{
		for (j=0;j<=width-1;j++)
        {
            near12=cells[i-1][j-1] + cells[i-1][j] + cells[i-1][j+1]
            + cells[i][j-1] + cells[i][j+1] + cells[i+1][j-1] + cells[i+1][j] + cells[i+1][j+1];
            if(near12==3)
                cells2[i][j]=1;
            else if(near12==2)
                cells2[i][j]=cells[i][j];
            else
                cells2[i][j]=0;
        }

	}
	for (i=0;i<=high-1;i++)
		for (j=0;j<=width-1;j++)
            cells[i][j]=cells2[i][j];
}

void main()
{
	start();
	while (1)
	{
	    show();
		input();
		outinput();
	}
}
